import Choice from './choice-dialog.html';

import list from './tpl/list.html';
import tr from './tpl/tr.html';
import form from './tpl/form.html';

import './choice-dialog.scss';

import Util from '../util/util.js';
/**
 * Created with JetBrains WebStorm.
 * User: liyong.wang
 * Date: 2017/11/15
 * Time: 上午11:29
 * Desc: 条件筛选弹窗组件
 *
 * var choiceDialog = new ChoiceDialog({
 *  title:'选择销售公司信息', //标题
 *  filter:[{name:'销售组织',column:'aaa'},{name:'公司名称',column:'companyName'}], //筛选条件
 *  table:[{name:'编号',column:'id'},{name:'销售组织',column:'aaa'},{name:'公司名称',column:'companyName'}],//表格头以及列名
 *  url:'//127.0.0.1:8088/xxx/xxx',//后台请求地址
 *  select:'radio',//是否有选项 false 无  radio 单选  checkbox 复选
 *  complete:function(select){ //点击确定后回调  select为所选内容
 *      console.log(select);
 *  },
 *  init:function(ele,obj){ //初始化回调，ele为弹窗对象  obj为dialog对象
 *      console.log(ele,obj);
 *  }
 * });
 *
 * choiceDialog.show(); //调用show方法显示弹窗
 */
export default function ChoiceDialog(options) {
    var _this = this , randomId = parseInt(Math.random() * 100000000),checkedLi=[];
    var baseOption = {
        title:'标题',
        filter:[],
        table:[],
        pages:['pageNO','pageSize'],
        page:{},
        select:false,
        init:function(){},
        complete:function(){}
    }
    options = $.extend(baseOption,options);
    options.page[options.pages[0]] = 1;
    options.page[options.pages[1]] = 10;

    if(options.filter.length == 0){
        console.error('参数错误，filter参数为空！');
        return;
    }
    if(options.table.length == 0){
        console.error('参数错误，table参数为空！');
        return;
    }
    if(!options.url){
        console.error('参数错误，url参数为空！');
        return;
    }

    this.init = function(options){
        var $baseElement = $(Choice()),tableEle = [];
        $baseElement.find('.modal-title').html(options.title);
        $baseElement.find('.modal-form').html(_this.createFormElement(options.filter));
        $baseElement.find('.modal-table').html(_this.createTableElement(options.table,options.select));
        $baseElement.find('.modal-table tbody').append(_this.createTrElement(options.table,options.select));
        $('body').append($baseElement);
        if(options.filter && options.filter.length > 2){
            $baseElement.find('.modal-table').css({height:240});
        }
        //全选反选逻辑
        if(options.select && options.select == 'checkbox'){
            $('.modal.choice').on("click", '.check-all', function(){
                checkedLi = [];
                var childs = $('.checks');
                if(this.checked){
                    this.checked = true;
                    for(var i = 0; i < childs.length; i++){
                        childs[i].checked = true;
                    }
                }else{
                    this.checked = false
                    for(var i = 0; i < childs.length; i++){
                        childs[i].checked = false;
                    }
                }
                var checkedNum = $('.checks:checked');
                for(var i = 0; i < checkedNum.length; i ++){
                    checkedLi.push($(checkedNum[i]).data('row'));
                }
            });
            $('.modal.choice').on("click", '.checks', function(){
                checkedLi = [];
                var childs = $('.checks');
                var checkedNum = $('.checks:checked');
                if(checkedNum.length == childs.length){
                    $('.check-all')[0].checked = true;
                }else{
                    $('.check-all')[0].checked = false;
                }
                for(var i = 0; i < checkedNum.length; i ++){
                    checkedLi.push($(checkedNum[i]).data('row'));
                }
            });
        }else if(options.select && options.select == 'radio'){ //单选逻辑
            $('.modal.choice').on("click", '.radios', function(){
                checkedLi = $('.radios:checked').data('row');
            });
        }

        //点击确定
        $('.choice .confirm').on('click',function(){
            if(options.select && options.select == 'checkbox'){
                if(checkedLi && checkedLi.length == 0){
                    Util.alertMessage('请选择列表信息');
                    return;
                }
            }else if(options.select && options.select == 'radio'){
                if(!checkedLi || checkedLi == null || checkedLi.length == 0){
                    Util.alertMessage('请选择列表信息');
                    return;
                }
            }
            if(options.complete){
                _this.close();
                options.complete(checkedLi);
            }
        });
        //初始化回调
        if(options.init){
            options.init($baseElement,this);
        }
    }



    this.createFormElement = function(paramsFilter){
        return form({filter:paramsFilter,randomId:randomId});
    }

    this.createTableElement = function(paramsTable,select){
        return list({header:paramsTable,select});
    }
    this.createTrElement = function(paramsTable,select){
        var data = this.readDataByParams(options.page);
        return tr({data:data.list,header:paramsTable,select});
    }

    this.isEnding = function(total){
        var totalPage = total % options.page[options.pages[1]] == 0 ? total / options.page[options.pages[1]] : parseInt(total / options.page[options.pages[1]]) + 1;
        return options.page[options.pages[0]] == totalPage;
    }

    this.readDataByParams = function(param){
       var result = [],total = 0;
       $.ajax({
           url:options.url,
           data:param,
           async:false,
           success:function(data){
               if(data && data.success){
                   result = data.result;
                   total = data.result.total;
                   window.setTimeout(function(){
                       if(_this.isEnding(total)){ //没有更多了
                           $('.modal.choice .load-more').html('没有更多了');
                       }else{
                           $('.modal.choice .load-more').html('<span>点击加载更多<i class="iconfont icon-jiantou"></i></span>');
                       }
                       if(total == 0){
                           $('.modal.choice .load-more').hide();
                       }else{
                           $('.modal.choice .load-more').show();
                       }
                   },100);
               }else{
                   Util.alertMessage(data.error);
               }
           }
       });
       return result;
    }

    this.init(options);

    //动态表单验证
    var v = $('#choice_'+randomId).easyform();
    v.success = function (ef){//验证成功
        var serializeObj = _this.serializeObject($('.choice.modal').find('.modal-form').find('form'));
        options.page[options.pages[0]] = 1;
        options.page[options.pages[1]] = 10;
        var paramAll = $.extend(options.page,serializeObj)
        var data = _this.readDataByParams(paramAll);
        $('.choice.modal').find('.modal-table tbody').html(tr({data:data.list,header:options.table,select:options.select}));
        $('.choice.modal').find('.modal-table').animate({scrollTop:0},0);
    }

    //点击加载下一页
    $(".modal.choice .load-more").on("click","span",function(e){
        var serializeObj = _this.serializeObject($('.choice.modal').find('.modal-form').find('form'));
        options.page[options.pages[0]] = parseInt(options.page[options.pages[0]] + 1);
        var paramAll = $.extend(options.page,serializeObj)
        var data = _this.readDataByParams(paramAll);
        $('.choice.modal').find('.modal-table tbody').append(tr({data:data.list,header:options.table,select:options.select}));
    });

    //清除按钮
    $('.choice.modal .choice-reset').on('click',function(){
        options.page[options.pages[0]] = 1;//重置页码
    })

    //关闭弹窗事件
    $('.choice .icon-shanchu,.choice .cancel').on('click',function(){
        _this.close();
    });

    this.selected = function(){
        return checkedLi;
    }

    this.show = function(){
        $('.modal.choice').show();
    }
    this.close = function(){
        $('.modal.choice').hide();
        $('.modal.choice').remove();
    }
    //序列化表单中的条件，如果未输入则为空
    this.serializeObject = function($form){
        var formArr = $form.serializeArray(),serializeObj = {};
        for(var i in formArr){
            serializeObj[formArr[i].name] = formArr[i].value;
        }
        return serializeObj;
    }

    return this;
}